<?php
/**
 * Popup to Add/Remove Patners to Centers
 *
 * @author Xavier VILAIN
 * @package
 * @license
 */

use Fox\Popup;
use Fox\Core\Errors;
use Fox\Generator;
use Nawa\MedicalStudy\MedicalCenter;
use Nawa\MedicalStudy\MedicalCenter\Partner;
use Nawa\Messages;
use Fox\Html\Input;
use Fox\Html\Block;
use Fox\Html\DropList;
use Fox\Html\Screen;

$xview = Xview::instance();
$msid = $xview->val('msid');
$medicalStudy = $xview->component('medicalstudies', 'medicalstudy');

$data = $xview->val('jsondata');
$customersId = null;
if(!empty($data))
{
	$data = json_decode($data,true);
	foreach($data['data'] as $item)
	{
		$customersId .= '::'.$item['customerid'];
	}
	unset($_GET['jsondata']);
}
$screen = new Screen('assignCenters','assign',Msg(Messages::BUNDLE,Messages::HELP_ASSIGN_TO_MC),true,
Generator::ajaxReload('MC_gPartners'));
$block = new Block('bAssignCenters',null);
$block->add(new DropList('medicalcenters',false,false,true))
->multiple()
->options($medicalStudy->medicalCentersPartners(),'mcid',
Generator::useFunction(function($data)
{
	return $data->medicalCenter()->name1;
}));
$block->add(new Input('customerids',false,$customersId))
->hidden();
$screen->add($block)->noLegend();
if($screen->submitted())
{

	$inputs = $screen->get();
	$customerids = $xview->val('customerids');
	if(empty($customerids))
	{
		Fox\Message::Error(Msg(Messages::BUNDLE,Messages::ERROR_NEED_TO_PICK_A_PARTNER));
	}
	else
	{
		$data = explode('::',$xview->val('customerids'));
		foreach($inputs['medicalcenters'] as $mcid)
		{
			try {
				/* @var $msMedicalCenter \Nawa\MedicalStudy\MedicalCenter */
				$msMedicalCenter = \Fox\Dao::load(MedicalCenter::className(),"$msid:$mcid");
				foreach($data as $customerid)
				{
					if(empty($customerid)) {
						continue;
					}
					$mcPartner = $msMedicalCenter->findPartners("$msid:$mcid:$customerid");
					$mcPartner->setFields(array(
									'msid' => $msid,
									'mcid' => $mcid,
									'customerid' => $customerid,
									'role' => Partner::ROLE_STANDARD,
									'uname' => User::current()->getId(),
									'udate' => Partner::sqlDateTime(time())));
					if($mcPartner->exists()) {
						$mcPartner->update();
					} else {
						$mcPartner->create();
					}
				}
				//$msMedicalCenter->update();
			}
			catch (Fox\Object\Exception\Save $e)
			{
				\Fox\Message::Error($e);
			}
		}
		echo Xview::instance()->messages();
		exit;
	}
}
$popup = new Popup('pAttach',Msg(Messages::BUNDLE,Messages::ASSIGN_TO_CENTERS),$screen);
if($screen->errors())
{
	echo Xview::instance()->messages();
}
else
{
	echo $popup->display();
}